import { Bookmark, BookmarkTreeNode, Category } from '../types';
import { analyzeBookmark } from '../services/apiService';

// 预定义分类
const DEFAULT_CATEGORIES: Category[] = [
  { id: '1', name: '科技' },
  { id: '2', name: '教育' },
  { id: '3', name: '娱乐' },
  { id: '4', name: '社交' },
  { id: '5', name: '新闻' },
  { id: '6', name: '购物' },
  { id: '7', name: '工具' },
  { id: '8', name: '其他' }
];

// 获取书签
export const getBookmarks = async (): Promise<BookmarkTreeNode[]> => {
  return new Promise((resolve, reject) => {
    chrome.bookmarks.getTree((results) => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
      } else {
        resolve(results);
      }
    });
  });
};

// 递归获取所有书签
export const fetchBookmarks = async (): Promise<BookmarkTreeNode[]> => {
  const bookmarkTree = await getBookmarks();
  const bookmarks: BookmarkTreeNode[] = [];
  
  // 递归提取书签
  const extractBookmarks = (nodes: BookmarkTreeNode[]) => {
    for (const node of nodes) {
      if (node.url) {
        bookmarks.push(node);
      }
      if (node.children) {
        extractBookmarks(node.children);
      }
    }
  };
  
  extractBookmarks(bookmarkTree);
  return bookmarks;
};

// 对书签进行分类
export const categorizeBookmarks = async (
  bookmarkNodes: BookmarkTreeNode[]
): Promise<{ categorizedBookmarks: Bookmark[], allCategories: Category[] }> => {
  // 获取自定义分类
  const customCategories = await loadCustomCategories();
  const allCategories = [...DEFAULT_CATEGORIES, ...customCategories];
  
  // 获取API密钥
  const apiKey = await getApiKey();
  
  // 转换并分类每个书签
  const promises = bookmarkNodes.map(async (node) => {
    if (!node.url) return null;
    
    let categoryId = '8'; // 默认为"其他"分类
    
    try {
      // 如果存在API密钥，尝试使用API进行分类
      if (apiKey) {
        const analysis = await analyzeBookmark(node.title, node.url, apiKey);
        // 找到匹配的分类
        const matchedCategory = allCategories.find(cat => 
          cat.name.toLowerCase() === analysis.category.toLowerCase()
        );
        if (matchedCategory) {
          categoryId = matchedCategory.id;
        }
      } else {
        // 如果没有API密钥，使用简单规则进行分类
        categoryId = categorizeByRules(node.title, node.url, allCategories);
      }
    } catch (error) {
      console.error('分类书签时出错:', error);
      // 出错时使用简单规则
      categoryId = categorizeByRules(node.title, node.url, allCategories);
    }
    
    return {
      id: node.id,
      title: node.title,
      url: node.url,
      dateAdded: node.dateAdded,
      categoryId,
      parentId: node.parentId || null
    } as Bookmark;
  });
  
  const bookmarks = (await Promise.all(promises)).filter(Boolean) as Bookmark[];
  return { categorizedBookmarks: bookmarks, allCategories };
};

// 使用简单规则对书签进行分类
const categorizeByRules = (title: string, url: string, categories: Category[]): string => {
  const lowerTitle = title.toLowerCase();
  const lowerUrl = url.toLowerCase();
  
  // 简单规则匹配
  if (lowerUrl.includes('github') || lowerUrl.includes('stackoverflow') || 
      lowerTitle.includes('code') || lowerTitle.includes('programming')) {
    return '1'; // 科技
  }
  
  if (lowerUrl.includes('learn') || lowerUrl.includes('course') || 
      lowerTitle.includes('tutorial') || lowerTitle.includes('教程')) {
    return '2'; // 教育
  }
  
  if (lowerUrl.includes('youtube') || lowerUrl.includes('netflix') || 
      lowerUrl.includes('game') || lowerTitle.includes('movie')) {
    return '3'; // 娱乐
  }
  
  if (lowerUrl.includes('facebook') || lowerUrl.includes('twitter') || 
      lowerUrl.includes('instagram') || lowerUrl.includes('linkedin')) {
    return '4'; // 社交
  }
  
  if (lowerUrl.includes('news') || lowerTitle.includes('新闻') || 
      lowerUrl.includes('bbc') || lowerUrl.includes('cnn')) {
    return '5'; // 新闻
  }
  
  if (lowerUrl.includes('amazon') || lowerUrl.includes('shop') || 
      lowerUrl.includes('store') || lowerTitle.includes('购物')) {
    return '6'; // 购物
  }
  
  if (lowerUrl.includes('tool') || lowerUrl.includes('app') || 
      lowerTitle.includes('工具') || lowerTitle.includes('应用')) {
    return '7'; // 工具
  }
  
  return '8'; // 其他
};

// 加载自定义分类
const loadCustomCategories = async (): Promise<Category[]> => {
  return new Promise((resolve) => {
    chrome.storage.local.get(['customCategories'], (result) => {
      resolve(result.customCategories || []);
    });
  });
};

// 获取API密钥
const getApiKey = async (): Promise<string | null> => {
  return new Promise((resolve) => {
    chrome.storage.local.get(['apiKey'], (result) => {
      resolve(result.apiKey || null);
    });
  });
}; 